import { PageContainer } from '@ant-design/pro-layout';
import React, { useState } from 'react';
import { getList, addItem, updateItem } from '@/services/demo-service/demoapi';
import type { DemoDataItem } from '@/models/demo';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { ResultCode } from '@/services/dataResult';
import CreateForm from './components/CreateForm';
import { message } from 'antd';

const Page1: React.FC = () => {
  //表单状态
  const [modalVisible, handleModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<DemoDataItem>();
  //弹窗
  const showModal = (current: DemoDataItem) => {
    handleModalVisible(true);
    console.log(modalVisible);
    setCurrentRow(current);
  };
  //隐藏弹窗
  const hideModal = () => {
    handleModalVisible(false);
    setCurrentRow(undefined);
  };
  //提交
  const editSubmit = async (data: DemoDataItem) => {
    try {
      if (data.id) {
        await addItem(data);
      } else {
        await updateItem(data);
      }
      message.success('操作成功');
      hideModal();
    } catch (error) {
      console.log(error);
      message.error('提交失败');
    }
  };

  //列配置
  const columns: ProColumns<DemoDataItem>[] = [
    {
      title: 'Id',
      key: 'id',
      dataIndex: 'id',
      width: 100,
    },
    {
      title: '名称',
      dataIndex: 'name',
      width: 150,
    },
    {
      title: '描述',
      dataIndex: 'description',
      width: 300,
      search: false, //默认会设置搜索条件
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 100,
      render: (_, current) => {
        return (
          <a
            onClick={() => {
              showModal(current);
            }}
          >
            编辑
          </a>
        );
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable<DemoDataItem, API.PageParams>
        columns={columns}
        rowKey={(record) => record.id}
        request={async (params = {}) => {
          const data = await getList(params);
          return {
            data: data.data,
            success: data.code == ResultCode.Success,
            total: data.total,
          };
        }}
      />
      <CreateForm
        visible={modalVisible}
        data={currentRow}
        onSubmit={editSubmit}
        onCancel={hideModal}
      />
    </PageContainer>
  );
};

export default Page1;
